import { users, getBeds, getRooms } from './database.mjs'
export const searchRooms = ({
  type = 'student',
  school,
  building,
  floor,
  search,
  sex,
  enable,
  pageNum = 1,
  pageSize = 10
} = {}) => {
  const userFilter = users.filter((u) => u.type == type)
  let bedList = getBeds(type)
  if (school) {
    bedList = bedList.filter((b) => b.school == school)
  }
  if (building) {
    bedList = bedList.filter((b) => b.building == building)
  }
  if (floor) {
    bedList = bedList.filter((b) => b.floor == floor)
  }
  bedList = bedList.map((b) => ({ ...b, user: userFilter.find((u) => u.bed == b.id) }))
  if (search) {
    bedList = bedList.filter((b) =>
      [b.schoolName, b.buildingName, b.floorName, b.roomName, b.name, b.user?.name]
        .filter((str) => ![undefined, null, ''].includes(str))
        .some((str) => str.includes(search))
    )
  }
  if (sex) {
    bedList = bedList.filter((b) => b.user && b.user.sex == sex)
  }
  if ([0, 1, '0', '1'].includes(enable)) {
    bedList = bedList.filter((b) => b.user && b.enable == enable)
  }

  let roomList = getRooms(type)

  roomList = roomList.map((r) => ({
    ...r,
    beds: bedList.filter((b) => b.room == r.id)
  }))

  roomList = roomList.filter((r) => r.beds && r.beds.length > 0)

  const end = pageNum * pageSize
  const start = end - pageSize
  return {
    total: roomList.length,
    list: roomList.slice(start, end)
  }
}
